<?php
/**
 * Created by PhpStorm.
 * User: xiaoxin
 * Date: 2018/10/19 0019
 * Time: 20:53
 */

namespace app\index\controller;
use app\index\model\User;
use think\Controller;
use think\captcha\Captcha;
use think\Loader;
use alimsg\Msg;

class Reg extends Controller
{
	/**
	 * 注册页面主页
	 * @return mixed
	 */
	public function index(){
		return $this->fetch();
	}

	/**
	 * 添加用户/注册用户
	 */
	public function addUser()
	{
		$post = input('');
		$validate = Loader::validate('AddUserCheck');
		if(!$validate->check($post)){
			$this->error($validate->getError());
		}
		if (strlen($post['phoneCode'])>4){
			$this->error('手机验证码错误');
		}
		if ($post['phoneCode']!=session('code')['num']){
			$this->error('手机验证码错误');
		}
		$post['ctime'] = time();
		$post['password'] = md5($post['password']);
		$res = User::create($post);
		if ($res){
			session('code',null);
			$this->success('注册成功');
		}else{
			$this->error('注册失败，请稍后在试');
		}

	}
	/**
	 * 获取短信验证码
	 */
	public function phoneCode(){
		$data = input('post.');
		$validate = Loader::validate('PhoneCheckCode');
		if(!$validate->check($data)){
			$this->error($validate->getError());
		}
		$data['ctime'] = time();
		$num = mt_rand(1000,9999);
		$res =  Msg::regMsg($data['phone'],$num);
		$data['num'] = $num;
		if ($res->Message=='OK'){
			session('code',$data);
			$this->success('已发送');
		}else{
			$this->error('发送失败、请稍后再试');
		}
	}


	/**
	 * 生成验证码
	 * @return \think\Response
	 */
	public function getCode(){
		$config =    [
			// 验证码字体大小
			'fontSize'    =>    200,
			// 验证码位数
			'length'      =>    3,
			// 关闭验证码杂点
			'useNoise'    =>    false,
		];
		$captcha = new Captcha($config);
		return $captcha->entry();
	}
}